/**
 * AI智能对话WebSocket管理器
 * 基于现代WebSocket服务设计理念，专为AI智能对话场景优化
 * 
 * @author AI Agent Team
 * @version 3.0.0
 * @description 提供企业级WebSocket连接管理解决方案
 * 
 * 核心特性：
 * - 🔄 单例模式，确保全应用唯一实例
 * - 📢 发布订阅模式，支持多组件消息订阅
 * - 🎯 类型化消息，智能路由不同消息类型
 * - 🔄 指数退避重连策略
 * - 💓 智能心跳检测机制
 * - 📝 消息队列与优先级处理
 * - 🎭 Mock模式，完美支持开发测试
 * - 🧠 深度思考，AI高级功能支持
 * - 📊 连接状态监控和统计
 * - 🗜️ 智能消息压缩
 * - 🎪 事件驱动架构
 */

/**
 * @typedef {Object} WebSocketConfig WebSocket配置对象
 * @property {string} [url] WebSocket连接地址
 * @property {string} [token] 认证令牌
 * @property {boolean} [mockMode=false] 是否启用Mock模式
 * @property {string} [historyId] 对话历史ID
 * @property {string} [agentId] AI智能体ID
 * @property {Function} [mockWebSocketFunction] Mock WebSocket实现函数
 * @property {ReconnectConfig} [reconnect] 重连配置
 * @property {HeartbeatConfig} [heartbeat] 心跳配置
 * @property {CompressionConfig} [compression] 压缩配置
 * @property {QueueConfig} [queue] 队列配置
 * @property {LoggingConfig} [logging] 日志配置
 */

/**
 * @typedef {Object} ReconnectConfig 重连配置
 * @property {boolean} [enabled=true] 是否启用自动重连
 * @property {number} [maxAttempts=5] 最大重连尝试次数
 * @property {number} [baseDelay=2000] 基础延迟时间（毫秒）
 * @property {number} [maxDelay=30000] 最大延迟时间（毫秒）
 * @property {boolean} [useExponentialBackoff=true] 是否使用指数退避
 */

/**
 * @typedef {Object} HeartbeatConfig 心跳配置
 * @property {boolean} [enabled=true] 是否启用心跳
 * @property {number} [interval=20000] 心跳间隔（毫秒）
 * @property {string|Object} [message='ping'] 心跳消息内容
 * @property {number} [timeout=5000] 心跳响应超时时间（毫秒）
 * @property {number} [loseLimit=3] 允许丢失心跳的最大次数
 */

/**
 * @typedef {Object} CompressionConfig 压缩配置
 * @property {boolean} [enabled=false] 是否启用消息压缩
 * @property {number} [threshold=1024] 压缩阈值（字节）
 * @property {string} [algorithm='simple'] 压缩算法
 */

/**
 * @typedef {Object} QueueConfig 队列配置
 * @property {boolean} [enabled=true] 是否启用消息队列
 * @property {number} [maxSize=100] 队列最大长度
 * @property {boolean} [persistOnReconnect=true] 重连时是否保持队列
 */

/**
 * @typedef {Object} LoggingConfig 日志配置
 * @property {boolean} [enabled=true] 是否启用日志
 * @property {string} [level='info'] 日志级别: debug|info|warn|error
 * @property {string} [prefix='[WebSocketManager]'] 日志前缀
 */

/**
 * @typedef {Object} TypedMessage 类型化消息
 * @property {string} type 消息类型
 * @property {*} payload 消息载荷
 * @property {number} timestamp 时间戳
 * @property {string} [id] 消息ID
 * @property {Object} [meta] 元数据
 */

/**
 * WebSocket管理器类 - 企业级解决方案
 */
class WebSocketManager {
	/**
	 * 单例实例存储
	 * @private
	 * @static
	 */
	static _instance = null;
	
	/**
	 * 单例锁，防止并发创建多个实例
	 * @private
	 * @static
	 */
	static _lock = false;
	
	/**
	 * 获取WebSocketManager单例实例
	 * @param {WebSocketConfig} [config] 配置选项
	 * @returns {WebSocketManager} 单例实例
	 */
	static getInstance(config = {}) {
		if (!WebSocketManager._instance && !WebSocketManager._lock) {
			WebSocketManager._lock = true;
			WebSocketManager._instance = new WebSocketManager(config);
			WebSocketManager._lock = false;
		} else if (config && Object.keys(config).length > 0) {
			// 如果实例已存在但传入了新配置，则更新配置
			WebSocketManager._instance.updateConfig(config);
		}
		return WebSocketManager._instance;
	}
	
	/**
	 * 销毁单例实例
	 * @static
	 */
	static destroyInstance() {
		if (WebSocketManager._instance) {
			WebSocketManager._instance.destroy();
			WebSocketManager._instance = null;
		}
	}
	
	/**
	 * 构造函数 - 私有化，通过getInstance访问
	 * @param {WebSocketConfig} config 配置选项
	 */
	constructor(config = {}) {
		// 防止外部直接实例化
		if (WebSocketManager._instance) {
			throw new Error('WebSocketManager是单例模式，请使用getInstance()方法获取实例');
		}
		
		// ==================== 基础配置初始化 ====================
		this.config = this._mergeDefaultConfig(config);
		this.connectionId = this._generateConnectionId();
		
		// ==================== 连接状态管理 ====================
		this.socketTask = null;
		this.isConnected = false;
		this.connectionState = 'disconnected'; // disconnected|connecting|connected|reconnecting
		this.lastConnectTime = 0;
		this.totalUptime = 0;
		
		// ==================== 重连机制 ====================
		this.reconnectLock = false;
		this.currentReconnectAttempts = 0;
		this.reconnectTimer = null;
		this.reconnectStartTime = 0;
		
		// ==================== 心跳机制 ====================
		this.heartbeatTimer = null;
		this.heartbeatTimeoutTimer = null;
		this.lastHeartbeatTime = 0;
		this.heartbeatLoseCount = 0;
		this.heartbeatStats = {
			sent: 0,
			received: 0,
			lost: 0,
			avgResponseTime: 0
		};
		
		// ==================== 发布订阅系统 ====================
		this.subscriptions = new Map(); // 消息类型 -> 回调函数数组
		this.globalSubscriptions = []; // 全局消息监听器
		
		// ==================== 事件系统 ====================
		this.eventListeners = {
			connected: [],
			disconnected: [],
			error: [],
			message: [],
			reconnecting: [],
			reconnected: [],
			heartbeatTimeout: [],
			stateChange: []
		};
		
		// ==================== 消息队列系统 ====================
		this.messageQueue = [];
		this.priorityQueue = []; // 高优先级消息队列
		this.queueProcessing = false;
		
		// ==================== 统计和监控 ====================
		this.stats = {
			connections: 0,
			reconnections: 0,
			messagesReceived: 0,
			messagesSent: 0,
			errors: 0,
			totalDataReceived: 0,
			totalDataSent: 0,
			avgMessageSize: 0,
			startTime: Date.now(),
			lastErrorTime: 0,
			lastErrorMessage: ''
		};
		
		// ==================== AI对话专属功能 ====================
		this.deepThinkMode = false;
		this.deepThinkStartTime = 0;
		this.aiResponseBuffers = new Map(); // 流式响应缓冲
		
		// ==================== 消息压缩 ====================
		this.compressionSupported = this.config.compression.enabled;
		this.compressionStats = {
			totalOriginalSize: 0,
			totalCompressedSize: 0,
			compressionRatio: 0,
			messagesCompressed: 0
		};
		
		// ==================== 性能优化 ====================
		this.batchSendTimer = null;
		this.batchSendQueue = [];
		this.performanceMonitor = {
			connectionTimes: [],
			messageTimes: [],
			averageLatency: 0
		};
		
		// 初始化完成
		this._log('info', 'WebSocketManager单例实例创建完成', {
			connectionId: this.connectionId,
			config: this._sanitizeConfigForLog(this.config)
		});
	}
	
	/**
	 * 合并默认配置
	 * @private
	 * @param {WebSocketConfig} userConfig 用户配置
	 * @returns {WebSocketConfig} 合并后的配置
	 */
	_mergeDefaultConfig(userConfig) {
		const defaultConfig = {
			url: '',
			token: '',
			mockMode: false,
			historyId: '',
			agentId: '',
			mockWebSocketFunction: null,
			
			reconnect: {
				enabled: true,
				maxAttempts: 5,
				baseDelay: 2000,
				maxDelay: 30000,
				useExponentialBackoff: true
			},
			
			heartbeat: {
				enabled: true,
				interval: 20000,
				message: { type: 'ping', timestamp: 0 },
				timeout: 5000,
				loseLimit: 3
			},
			
			compression: {
				enabled: false,
				threshold: 1024,
				algorithm: 'simple'
			},
			
			queue: {
				enabled: true,
				maxSize: 100,
				persistOnReconnect: true
			},
			
			logging: {
				enabled: true,
				level: 'info',
				prefix: '[WebSocketManager]'
			}
		};
		
		return this._deepMerge(defaultConfig, userConfig);
	}
	
	/**
	 * 深度合并对象
	 * @private
	 * @param {Object} target 目标对象
	 * @param {Object} source 源对象
	 * @returns {Object} 合并后的对象
	 */
	_deepMerge(target, source) {
		const result = { ...target };
		
		for (const key in source) {
			if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
				result[key] = this._deepMerge(target[key] || {}, source[key]);
			} else {
				result[key] = source[key];
			}
		}
		
		return result;
	}
	
	/**
	 * 更新配置
	 * @param {WebSocketConfig} newConfig 新配置
	 */
	updateConfig(newConfig) {
		const oldConfig = { ...this.config };
		this.config = this._deepMerge(this.config, newConfig);
		
		this._log('info', '配置已更新', {
			changed: this._getConfigChanges(oldConfig, this.config)
		});
		
		// 如果连接相关配置改变，需要重新连接
		if (this._shouldReconnectOnConfigChange(oldConfig, this.config)) {
			this._log('info', '检测到连接配置变化，准备重新连接');
			this.reconnect();
		}
	}
	
	/**
	 * 检查配置变化是否需要重连
	 * @private
	 * @param {Object} oldConfig 旧配置
	 * @param {Object} newConfig 新配置
	 * @returns {boolean} 是否需要重连
	 */
	_shouldReconnectOnConfigChange(oldConfig, newConfig) {
		const criticalFields = ['url', 'token', 'mockMode', 'historyId', 'agentId'];
		return criticalFields.some(field => oldConfig[field] !== newConfig[field]);
	}
	
	/**
	 * 获取配置变化详情
	 * @private
	 * @param {Object} oldConfig 旧配置
	 * @param {Object} newConfig 新配置
	 * @returns {Array} 变化列表
	 */
	_getConfigChanges(oldConfig, newConfig) {
		const changes = [];
		const checkChanges = (old, new_, path = '') => {
			for (const key in new_) {
				const currentPath = path ? `${path}.${key}` : key;
				if (typeof new_[key] === 'object' && new_[key] !== null && !Array.isArray(new_[key])) {
					checkChanges(old[key] || {}, new_[key], currentPath);
				} else if (old[key] !== new_[key]) {
					changes.push({
						field: currentPath,
						oldValue: old[key],
						newValue: new_[key]
					});
				}
			}
		};
		
		checkChanges(oldConfig, newConfig);
		return changes;
	}
	
	// ==================== 连接管理方法 ====================
	
	/**
	 * 连接到WebSocket服务器
	 * @param {string} [url] WebSocket地址，不传则使用配置中的地址
	 * @returns {Promise<void>} 连接Promise
	 */
	async connect(url) {
		if (url) {
			this.config.url = url;
		}
		
		if (!this.config.url && !this.config.mockMode) {
			throw new Error('未设置WebSocket连接地址');
		}
		
		if (this.isConnected) {
			this._log('warn', '已有活跃连接，跳过重复连接');
			return;
		}
		
		this._setState('connecting');
		const connectStartTime = Date.now();
		
		try {
			this._log('info', '开始建立WebSocket连接', {
				url: this.config.mockMode ? 'Mock模式' : this._sanitizeUrl(this.config.url),
				mockMode: this.config.mockMode
			});
			
			// Mock模式：直接进入连接状态，不需要真实连接
			if (this.config.mockMode) {
				await this._connectMockMode(connectStartTime);
			} else {
				// 正式模式：建立真实连接
				await this._connectRealMode(connectStartTime);
			}
			
		} catch (error) {
			this._setState('disconnected');
			this._updateErrorStats(error);
			this._log('error', 'WebSocket连接失败', error);
			throw error;
		}
	}
	
	/**
	 * Mock模式连接处理
	 * 完全不建立真实连接，纯粹使用模拟数据
	 * @private
	 * @param {number} connectStartTime 连接开始时间
	 */
	async _connectMockMode(connectStartTime) {
		this._log('info', 'Mock模式：完全模拟连接，不建立真实WebSocket', {
			agentId: this.config.agentId,
			historyId: this.config.historyId
		});
		
		// Mock模式下不创建任何真实WebSocket实例
		this.socketTask = null;
		
		// 直接设置为连接状态
		this._setState('connected');
		this.lastConnectTime = Date.now();
		this.stats.connections++;
		this.performanceMonitor.connectionTimes.push(Date.now() - connectStartTime);
		
		// 立即触发连接成功事件
		this._emit('connected', { 
			type: 'open', 
			timeStamp: Date.now(),
			connectionId: this.connectionId,
			mockMode: true
		});
		
		// 刷新消息队列（如果有的话）
		this._flushMessageQueue();
		
		this._log('info', 'Mock模式连接建立完成，完全模拟，无真实WebSocket连接');
	}
	
	/**
	 * 正式模式连接处理
	 * 建立真实的WebSocket连接
	 * @private
	 * @param {number} connectStartTime 连接开始时间
	 */
	async _connectRealMode(connectStartTime) {
		// 创建真实WebSocket实例
		await this._createSocketInstance();
		
		// 设置事件监听器
		this._setupEventListeners();
		
		// 更新统计信息
		this.lastConnectTime = Date.now();
		this.stats.connections++;
		this.performanceMonitor.connectionTimes.push(Date.now() - connectStartTime);
		
		this._log('info', 'WebSocket连接初始化完成');
	}
	
	/**
	 * 断开WebSocket连接
	 * @param {number} [code=1000] 关闭代码
	 * @param {string} [reason='手动断开'] 关闭原因
	 */
	disconnect(code = 1000, reason = '手动断开') {
		this._log('info', '开始断开WebSocket连接', { 
			code, 
			reason, 
			mockMode: this.config.mockMode 
		});
		
		// 停止重连和心跳
		this._stopReconnect();
		this._stopHeartbeat();
		
		// 关闭连接
		if (this.socketTask) {
			try {
				if (this.config.mockMode) {
					// Mock模式下安全关闭（如果有Mock实例）
					this._log('debug', 'Mock模式断开连接');
					if (typeof this.socketTask.close === 'function') {
						this.socketTask.close({ code, reason });
					}
				} else {
					// 正式模式关闭真实WebSocket
					this.socketTask.close({ code, reason });
				}
			} catch (error) {
				this._log('warn', '关闭连接时发生错误', error);
			}
			this.socketTask = null;
		} else if (this.config.mockMode) {
			// Mock模式下即使没有socketTask也要正常处理断开流程
			this._log('debug', 'Mock模式断开连接（无WebSocket实例）');
		}
		
		// 更新状态
		this._setState('disconnected');
		this._updateUptime();
		
		this._emit('disconnected', { 
			code, 
			reason, 
			manual: true, 
			mockMode: this.config.mockMode 
		});
	}
	
	/**
	 * 重连到WebSocket服务器
	 * @returns {Promise<void>} 重连Promise
	 */
	async reconnect() {
		this._log('info', '执行手动重连');
		
		// 重置重连状态
		this.currentReconnectAttempts = 0;
		this.reconnectLock = false;
		
		// 停止现有连接
		this.disconnect(1000, '手动重连');
		
		// 等待短暂延迟后重新连接
		await this._delay(500);
		return this.connect();
	}
	
	// ==================== 消息发送方法 ====================
	
	/**
	 * 发送原始消息
	 * @param {string|Object} message 消息内容
	 * @param {Object} [options] 发送选项
	 * @param {boolean} [options.priority=false] 是否为高优先级消息
	 * @param {number} [options.timeout=10000] 发送超时时间
	 * @param {boolean} [options.compress] 是否压缩消息
	 * @returns {Promise<string>} 发送结果
	 */
	async send(message, options = {}) {
		const sendOptions = {
			priority: false,
			timeout: 10000,
			compress: undefined,
			...options
		};
		
		// 准备消息数据
		const messageData = typeof message === 'string' ? message : JSON.stringify(message);
		const messageId = this._generateMessageId();
		
		this._log('debug', '准备发送消息', {
			messageId,
			length: messageData.length,
			options: sendOptions
		});
		
		// 检查连接状态
		if (!this.isConnected) {
			if (this.config.queue.enabled) {
				return this._queueMessage(messageData, sendOptions);
			} else {
				throw new Error('WebSocket未连接且消息队列已禁用');
			}
		}
		
		// 压缩消息（如果需要）
		const finalMessage = await this._processMessageForSending(messageData, sendOptions);
		
		// 执行发送
		return this._executeSend(finalMessage, sendOptions, messageId);
	}
	
	/**
	 * 发送类型化消息
	 * @param {string} type 消息类型
	 * @param {*} payload 消息载荷
	 * @param {Object} [options] 发送选项
	 * @returns {Promise<string>} 发送结果
	 */
	async sendTypedMessage(type, payload, options = {}) {
		const typedMessage = {
			type,
			payload,
			timestamp: Date.now(),
			id: this._generateMessageId(),
			meta: options.meta || {}
		};
		
		// AI对话专属逻辑
		if (type === 'ai_chat' && payload.deepThink) {
			this.deepThinkMode = true;
			this.deepThinkStartTime = Date.now();
			this._log('info', '启用深度思考模式', { messageId: typedMessage.id });
		}
		
		return this.send(typedMessage, options);
	}
	
	/**
	 * 发送AI对话消息（便捷方法）
	 * @param {string} content 对话内容
	 * @param {Object} [aiOptions] AI选项
	 * @param {boolean} [aiOptions.deepThink=false] 是否启用深度思考
	 * @param {boolean} [aiOptions.webSearch=false] 是否启用联网搜索
	 * @param {Object} [sendOptions] 发送选项
	 * @returns {Promise<string>} 发送结果
	 */
	async sendAIMessage(content, aiOptions = {}, sendOptions = {}) {
		const payload = {
			content,
			deepThink: aiOptions.deepThink || false,
			webSearch: aiOptions.webSearch || false,
			agentId: this.config.agentId,
			historyId: this.config.historyId,
			...aiOptions
		};
		
		return this.sendTypedMessage('ai_chat', payload, sendOptions);
	}
	
	// ==================== 发布订阅系统 ====================
	
	/**
	 * 订阅特定类型的消息
	 * @param {string} type 消息类型，使用 '*' 订阅所有消息
	 * @param {Function} callback 回调函数 (payload, message) => void
	 * @returns {Function} 取消订阅函数
	 */
	subscribe(type, callback) {
		if (typeof callback !== 'function') {
			throw new Error('回调函数必须是function类型');
		}
		
		if (type === '*') {
			// 全局订阅
			this.globalSubscriptions.push(callback);
			this._log('debug', '添加全局消息订阅', { callbackName: callback.name });
			
			return () => {
				const index = this.globalSubscriptions.indexOf(callback);
				if (index > -1) {
					this.globalSubscriptions.splice(index, 1);
					this._log('debug', '移除全局消息订阅');
				}
			};
		} else {
			// 类型化订阅
			if (!this.subscriptions.has(type)) {
				this.subscriptions.set(type, []);
			}
			
			this.subscriptions.get(type).push(callback);
			this._log('debug', '添加类型化消息订阅', { 
				type, 
				callbackName: callback.name,
				totalSubscribers: this.subscriptions.get(type).length 
			});
			
			return () => {
				const callbacks = this.subscriptions.get(type);
				if (callbacks) {
					const index = callbacks.indexOf(callback);
					if (index > -1) {
						callbacks.splice(index, 1);
						this._log('debug', '移除类型化消息订阅', { type });
						
						// 如果没有订阅者了，删除类型
						if (callbacks.length === 0) {
							this.subscriptions.delete(type);
						}
					}
				}
			};
		}
	}
	
	/**
	 * 取消订阅
	 * @param {string} type 消息类型
	 * @param {Function} [callback] 特定回调函数，不传则取消该类型的所有订阅
	 */
	unsubscribe(type, callback) {
		if (type === '*') {
			if (callback) {
				const index = this.globalSubscriptions.indexOf(callback);
				if (index > -1) {
					this.globalSubscriptions.splice(index, 1);
				}
			} else {
				this.globalSubscriptions = [];
			}
		} else {
			if (callback) {
				const callbacks = this.subscriptions.get(type);
				if (callbacks) {
					const index = callbacks.indexOf(callback);
					if (index > -1) {
						callbacks.splice(index, 1);
						if (callbacks.length === 0) {
							this.subscriptions.delete(type);
						}
					}
				}
			} else {
				this.subscriptions.delete(type);
			}
		}
		
		this._log('debug', '取消消息订阅', { type, hasCallback: !!callback });
	}
	
	/**
	 * 分发消息到订阅者
	 * @private
	 * @param {Object} message 消息对象
	 */
	_dispatchMessage(message) {
		try {
			// 尝试解析类型化消息
			let messageObj = message;
			if (typeof message.data === 'string') {
				try {
					messageObj = JSON.parse(message.data);
				} catch {
					// 非JSON消息，作为普通文本处理
					messageObj = { type: 'text', payload: message.data, raw: true };
				}
			}
			
			// 更新统计信息
			this.stats.messagesReceived++;
			this.stats.totalDataReceived += (message.data || '').length;
			
			// 处理AI对话特殊消息
			this._handleAIMessage(messageObj, message);
			
			// 分发给全局订阅者
			this.globalSubscriptions.forEach(callback => {
				try {
					callback(messageObj.payload || messageObj, message);
				} catch (error) {
					this._log('error', '全局订阅回调执行错误', error);
				}
			});
			
			// 分发给类型化订阅者
			if (messageObj.type) {
				const callbacks = this.subscriptions.get(messageObj.type);
				if (callbacks && callbacks.length > 0) {
					callbacks.forEach(callback => {
						try {
							callback(messageObj.payload || messageObj, message);
						} catch (error) {
							this._log('error', `类型化订阅回调执行错误 [${messageObj.type}]`, error);
						}
					});
				}
			}
			
			// 触发通用message事件
			this._emit('message', { message: messageObj, raw: message });
			
		} catch (error) {
			this._log('error', '消息分发失败', error);
		}
	}
	
	// ==================== 连接状态和事件管理 ====================
	
	/**
	 * 注册连接成功回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onConnected(callback) {
		return this._addEventListener('connected', callback);
	}
	
	/**
	 * 注册断开连接回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onDisconnected(callback) {
		return this._addEventListener('disconnected', callback);
	}
	
	/**
	 * 注册错误回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onError(callback) {
		return this._addEventListener('error', callback);
	}
	
	/**
	 * 注册重连开始回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onReconnecting(callback) {
		return this._addEventListener('reconnecting', callback);
	}
	
	/**
	 * 注册重连成功回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onReconnected(callback) {
		return this._addEventListener('reconnected', callback);
	}
	
	/**
	 * 注册状态变化回调
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消注册函数
	 */
	onStateChange(callback) {
		return this._addEventListener('stateChange', callback);
	}
	
	// ==================== 状态查询方法 ====================
	
	/**
	 * 获取当前连接状态
	 * @returns {Object} 状态信息
	 */
	getState() {
		return {
			isConnected: this.isConnected,
			connectionState: this.connectionState,
			connectionId: this.connectionId,
			url: this.config.mockMode ? 'Mock模式' : this._sanitizeUrl(this.config.url),
			mockMode: this.config.mockMode,
			lastConnectTime: this.lastConnectTime,
			uptime: this.lastConnectTime > 0 ? Date.now() - this.lastConnectTime : 0,
			totalUptime: this.totalUptime + (this.lastConnectTime > 0 ? Date.now() - this.lastConnectTime : 0),
			reconnectAttempts: this.currentReconnectAttempts,
			maxReconnectAttempts: this.config.reconnect.maxAttempts,
			queueLength: this.messageQueue.length,
			priorityQueueLength: this.priorityQueue.length,
			subscribersCount: this._getSubscribersCount(),
			deepThinkMode: this.deepThinkMode,
			heartbeatStats: { ...this.heartbeatStats }
		};
	}
	
	/**
	 * 获取连接统计信息
	 * @returns {Object} 统计信息
	 */
	getStats() {
		const currentTime = Date.now();
		const sessionDuration = currentTime - this.stats.startTime;
		
		return {
			...this.stats,
			sessionDuration,
			messagesPerSecond: sessionDuration > 0 ? this.stats.messagesReceived / (sessionDuration / 1000) : 0,
			avgConnectionTime: this._calculateAverage(this.performanceMonitor.connectionTimes),
			avgMessageLatency: this.performanceMonitor.averageLatency,
			compressionStats: { ...this.compressionStats },
			heartbeatStats: { ...this.heartbeatStats }
		};
	}
	
	/**
	 * 获取当前URL
	 * @returns {string} 当前连接URL
	 */
	getUrl() {
		return this.config.mockMode ? 'Mock模式' : this.config.url;
	}
	
	/**
	 * 获取消息队列长度
	 * @returns {number} 队列长度
	 */
	getQueueLength() {
		return this.messageQueue.length + this.priorityQueue.length;
	}
	
	/**
	 * 清空消息队列
	 * @param {boolean} [rejectPending=false] 是否拒绝队列中的待发送消息
	 */
	clearQueue(rejectPending = false) {
		const totalCleared = this.messageQueue.length + this.priorityQueue.length;
		
		if (rejectPending) {
			[...this.messageQueue, ...this.priorityQueue].forEach(item => {
				if (item.reject) {
					item.reject(new Error('消息队列已被清空'));
				}
			});
		}
		
		this.messageQueue = [];
		this.priorityQueue = [];
		
		this._log('info', '消息队列已清空', { clearedCount: totalCleared, rejectPending });
	}
	
	// ==================== 私有方法 ====================
	
	/**
	 * 生成连接ID
	 * @private
	 * @returns {string} 连接ID
	 */
	_generateConnectionId() {
		return `ws_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`;
	}
	
	/**
	 * 生成消息ID
	 * @private
	 * @returns {string} 消息ID
	 */
	_generateMessageId() {
		return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`;
	}
	
	/**
	 * 设置连接状态
	 * @private
	 * @param {string} state 状态
	 */
	_setState(state) {
		const oldState = this.connectionState;
		this.connectionState = state;
		this.isConnected = state === 'connected';
		
		if (oldState !== state) {
			this._log('info', `连接状态变化: ${oldState} -> ${state}`);
			this._emit('stateChange', { 
				oldState, 
				newState: state, 
				isConnected: this.isConnected 
			});
		}
	}
	
	/**
	 * 统一日志输出
	 * @private
	 * @param {string} level 日志级别
	 * @param {string} message 日志消息
	 * @param {*} [data] 附加数据
	 */
	_log(level, message, data = null) {
		if (!this.config.logging.enabled) return;
		
		const logLevels = { debug: 0, info: 1, warn: 2, error: 3 };
		const configLevel = logLevels[this.config.logging.level] || 1;
		const currentLevel = logLevels[level] || 1;
		
		if (currentLevel >= configLevel) {
			const timestamp = new Date().toISOString();
			const prefix = `${this.config.logging.prefix}[${this.connectionId}][${timestamp}]`;
			const logMessage = `${prefix} ${message}`;
			
			if (data) {
				console[level](logMessage, data);
			} else {
				console[level](logMessage);
			}
		}
	}
	
	/**
	 * 触发事件
	 * @private
	 * @param {string} eventName 事件名称
	 * @param {*} data 事件数据
	 */
	_emit(eventName, data) {
		const listeners = this.eventListeners[eventName];
		if (listeners && listeners.length > 0) {
			listeners.forEach(callback => {
				try {
					callback(data);
				} catch (error) {
					this._log('error', `事件监听器执行错误 [${eventName}]`, error);
				}
			});
		}
	}
	
	/**
	 * 添加事件监听器
	 * @private
	 * @param {string} eventName 事件名称
	 * @param {Function} callback 回调函数
	 * @returns {Function} 取消监听函数
	 */
	_addEventListener(eventName, callback) {
		if (!this.eventListeners[eventName]) {
			this.eventListeners[eventName] = [];
		}
		
		this.eventListeners[eventName].push(callback);
		
		return () => {
			const listeners = this.eventListeners[eventName];
			const index = listeners.indexOf(callback);
			if (index > -1) {
				listeners.splice(index, 1);
			}
		};
	}
	
	/**
	 * 延迟工具函数
	 * @private
	 * @param {number} ms 延迟毫秒数
	 * @returns {Promise} 延迟Promise
	 */
	_delay(ms) {
		return new Promise(resolve => setTimeout(resolve, ms));
	}
	
	/**
	 * 计算平均值
	 * @private
	 * @param {number[]} numbers 数字数组
	 * @returns {number} 平均值
	 */
	_calculateAverage(numbers) {
		if (numbers.length === 0) return 0;
		return numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
	}
	
	/**
	 * 获取订阅者总数
	 * @private
	 * @returns {Object} 订阅者统计
	 */
	_getSubscribersCount() {
		const typedCount = Array.from(this.subscriptions.values())
			.reduce((total, callbacks) => total + callbacks.length, 0);
		
		return {
			global: this.globalSubscriptions.length,
			typed: typedCount,
			total: this.globalSubscriptions.length + typedCount,
			types: this.subscriptions.size
		};
	}
	
	/**
	 * 清理敏感信息用于日志输出
	 * @private
	 * @param {string} url URL
	 * @returns {string} 清理后的URL
	 */
	_sanitizeUrl(url) {
		if (!url) return url;
		return url.replace(/\/\/[^/]*@/, '//***@').replace(/[?&]token=[^&]*/, '?token=***');
	}
	
	/**
	 * 清理配置信息用于日志输出
	 * @private
	 * @param {Object} config 配置对象
	 * @returns {Object} 清理后的配置
	 */
	_sanitizeConfigForLog(config) {
		return {
			...config,
			url: this._sanitizeUrl(config.url),
			token: config.token ? '***' : '',
			mockMode: config.mockMode
		};
	}
	
	/**
	 * 更新运行时间统计
	 * @private
	 */
	_updateUptime() {
		if (this.lastConnectTime > 0) {
			this.totalUptime += Date.now() - this.lastConnectTime;
			this.lastConnectTime = 0;
		}
	}
	
	/**
	 * 更新错误统计
	 * @private
	 * @param {Error} error 错误对象
	 */
	_updateErrorStats(error) {
		this.stats.errors++;
		this.stats.lastErrorTime = Date.now();
		this.stats.lastErrorMessage = error.message || error.toString();
	}
	
	/**
	 * 销毁实例，释放所有资源
	 */
	destroy() {
		this._log('info', '开始销毁WebSocketManager实例');
		
		// 断开连接
		this.disconnect(1000, '实例销毁');
		
		// 清理所有定时器
		this._stopReconnect();
		this._stopHeartbeat();
		this._stopBatchSend();
		
		// 清空消息队列
		this.clearQueue(true);
		
		// 清空订阅和事件监听
		this.subscriptions.clear();
		this.globalSubscriptions = [];
		Object.keys(this.eventListeners).forEach(key => {
			this.eventListeners[key] = [];
		});
		
		// 清理AI响应缓冲
		this.aiResponseBuffers.clear();
		
		this._log('info', 'WebSocketManager实例销毁完成');
	}
	
	/**
	 * 测试Mock模式连接（开发调试用）
	 * 快速验证Mock模式是否正常工作
	 * @returns {Promise<boolean>} 测试结果
	 */
	async testMockMode() {
		if (!this.config.mockMode) {
			this._log('warn', '当前不是Mock模式，无法执行Mock测试');
			return false;
		}
		
		try {
			this._log('info', '开始测试Mock模式连接...');
			
			// 测试连接
			await this.connect();
			
			if (!this.isConnected) {
				throw new Error('Mock连接失败');
			}
			
			// 测试消息发送
			const testResult = await this.sendAIMessage('测试Mock模式是否正常工作', {
				deepThink: true
			});
			
			this._log('info', 'Mock模式测试完成', {
				connected: this.isConnected,
				state: this.connectionState,
				sendResult: testResult
			});
			
			return true;
			
		} catch (error) {
			this._log('error', 'Mock模式测试失败', error);
			return false;
		}
	}
	
	// ==================== 缺失的私有方法实现 ====================
	
	/**
	 * 创建WebSocket实例（仅用于正式模式）
	 * @private
	 * @returns {Promise} 创建Promise
	 */
	async _createSocketInstance() {
		// 确保只在正式模式下创建WebSocket
		if (this.config.mockMode) {
			this._log('warn', 'Mock模式下不应该调用_createSocketInstance方法');
			return;
		}
		
		const wsUrl = this._buildUrl();
		this._log('info', '创建真实WebSocket连接', { url: this._sanitizeUrl(wsUrl) });
		this.socketTask = this._createRealWebSocket(wsUrl);
	}
	
	/**
	 * 创建真实WebSocket连接
	 * @private
	 * @param {string} url WebSocket URL
	 * @returns {Object} WebSocket实例
	 */
	_createRealWebSocket(url) {
		return uni.connectSocket({
			url: url,
			header: this.config.token ? {
				'Sec-WebSocket-Protocol': this.config.token
			} : {},
			success: () => {
				this._log('debug', 'WebSocket连接请求发送成功');
			},
			fail: (error) => {
				this._log('error', 'WebSocket连接请求失败', error);
				throw error;
			}
		});
	}
	
	/**
	 * 构建WebSocket连接URL
	 * @private
	 * @returns {string} 完整的WebSocket URL
	 */
	_buildUrl() {
		if (typeof this.config.url === 'function') {
			return this.config.url();
		}
		
		if (this.config.url.includes('${')) {
			return this.config.url
				.replace('${historyId}', this.config.historyId || '')
				.replace('${agentId}', this.config.agentId || '')
				.replace('${token}', this.config.token || '');
		}
		
		return this.config.url;
	}
	
	/**
	 * 设置WebSocket事件监听器（仅用于正式模式）
	 * @private
	 */
	_setupEventListeners() {
		// Mock模式下不需要设置事件监听器
		if (this.config.mockMode) {
			this._log('debug', 'Mock模式下跳过WebSocket事件监听器设置');
			return;
		}
		
		this._log('debug', '设置WebSocket事件监听器');
		
		// 安全检查
		if (!this.socketTask) {
			throw new Error('WebSocket实例未创建，无法设置事件监听器');
		}
		
		const requiredMethods = ['onOpen', 'onMessage', 'onClose', 'onError'];
		for (const method of requiredMethods) {
			if (typeof this.socketTask[method] !== 'function') {
				throw new Error(`WebSocket实例缺少必需方法: ${method}`);
			}
		}
		
		// 连接成功事件
		this.socketTask.onOpen((res) => {
			this._log('info', 'WebSocket连接成功建立');
			this._setState('connected');
			this.currentReconnectAttempts = 0;
			this.reconnectLock = false;
			this._stopReconnect();
			this._startHeartbeat();
			this._flushMessageQueue();
			this._emit('connected', { ...res, connectionId: this.connectionId });
		});
		
		// 消息接收事件
		this.socketTask.onMessage((res) => {
			this.stats.messagesReceived++;
			this.stats.totalDataReceived += (res.data || '').length;
			
			if (this._isHeartbeatResponse(res)) {
				this._handleHeartbeatResponse();
				return;
			}
			
			this._log('debug', '收到WebSocket消息', { dataLength: res.data?.length });
			this._dispatchMessage(res);
		});
		
		// 连接关闭事件
		this.socketTask.onClose((res) => {
			this._log('info', 'WebSocket连接关闭', res);
			this._setState('disconnected');
			this._stopHeartbeat();
			this._emit('disconnected', { ...res, connectionId: this.connectionId });
			
			if (res.code !== 1000) {
				this._handleReconnect();
			}
		});
		
		// 连接错误事件
		this.socketTask.onError((error) => {
			this._log('error', 'WebSocket连接错误', error);
			this._setState('disconnected');
			this._stopHeartbeat();
			this._updateErrorStats(error);
			this._emit('error', { ...error, connectionId: this.connectionId });
			this._handleReconnect();
		});
	}
	
	/**
	 * 执行消息发送
	 * @private
	 * @param {string} message 消息内容
	 * @param {Object} options 发送选项
	 * @param {string} messageId 消息ID
	 * @returns {Promise<string>} 发送结果
	 */
	async _executeSend(message, options, messageId) {
		// Mock模式下直接模拟发送成功，不需要真实WebSocket
		if (this.config.mockMode) {
			return this._executeMockSend(message, options, messageId);
		}
		
		// 正式模式：使用真实WebSocket发送
		return new Promise((resolve, reject) => {
			if (!this.socketTask) {
				reject(new Error('WebSocket实例未创建'));
				return;
			}
			
			let timeoutTimer = null;
			
			if (options.timeout > 0) {
				timeoutTimer = setTimeout(() => {
					reject(new Error(`发送超时（${options.timeout}ms）`));
				}, options.timeout);
			}
			
			const sendData = {
				data: message,
				success: () => {
					if (timeoutTimer) clearTimeout(timeoutTimer);
					this.stats.messagesSent++;
					this.stats.totalDataSent += message.length;
					this._log('debug', '消息发送成功', { messageId, length: message.length });
					resolve('发送成功');
				},
				fail: (error) => {
					if (timeoutTimer) clearTimeout(timeoutTimer);
					this._log('error', '消息发送失败', { messageId, error });
					reject(error);
				}
			};
			
			this.socketTask.send(sendData);
		});
	}
	
	/**
	 * Mock模式下执行消息发送
	 * 直接模拟发送成功并触发AI回答
	 * @private
	 * @param {string} message 消息内容
	 * @param {Object} options 发送选项
	 * @param {string} messageId 消息ID
	 * @returns {Promise<string>} 发送结果
	 */
	async _executeMockSend(message, options, messageId) {
		this._log('debug', 'Mock模式发送消息', {
			messageId,
			length: message.length,
			hasOptions: !!options
		});
		
		// 模拟发送成功
		this.stats.messagesSent++;
		this.stats.totalDataSent += message.length;
		
		// 异步触发Mock AI回答
		setTimeout(() => {
			this._triggerMockAIResponse(message, options);
		}, 100);
		
		this._log('debug', 'Mock消息发送成功', { messageId });
		return 'Mock发送成功';
	}
	
	/**
	 * 触发Mock AI回答
	 * 完全模拟AI回答流程，不依赖WebSocket
	 * @private
	 * @param {string} message 用户消息
	 * @param {Object} sendOptions 发送选项
	 */
	_triggerMockAIResponse(message, sendOptions) {
		try {
			// 记录发送选项用于调试
			this._log('debug', '触发Mock AI回答', {
				hasOptions: !!sendOptions,
				optionsKeys: sendOptions ? Object.keys(sendOptions) : []
			});
			
			// 解析消息以获取AI选项
			let aiOptions = {};
			let userContent = message;
			
			try {
				const parsedMessage = JSON.parse(message);
				if (parsedMessage.type === 'ai_chat' && parsedMessage.payload) {
					aiOptions = parsedMessage.payload;
					userContent = aiOptions.content || message;
				}
			} catch {
				// 如果不是JSON，直接使用原始消息
			}
			
			const hasDeepThink = aiOptions.deepThink === true;
			const hasWebSearch = aiOptions.webSearch === true;
			
			this._log('debug', '开始模拟AI回答', { 
				userContent: userContent.substring(0, 50) + '...',
				deepThink: hasDeepThink,
				webSearch: hasWebSearch
			});
			
			// 构建模拟响应步骤
			const responseSteps = [];
			
			// 深度思考流程
			if (hasDeepThink) {
				responseSteps.push(
					{ type: 'tag', data: '[SEEK]', delay: 500 },
					{ type: 'think', data: '正在进行深度思考...', delay: 1000 },
					{ type: 'think', data: '分析问题的多个维度...', delay: 1500 },
					{ type: 'think', data: '综合考虑各种因素...', delay: 2000 },
					{ type: 'tag', data: '[TEXT]', delay: 2500 }
				);
			} else {
				responseSteps.push({ type: 'tag', data: '[TEXT]', delay: 300 });
			}
			
			// 联网搜索模拟
			if (hasWebSearch) {
				responseSteps.push({
					type: 'search',
					data: '正在搜索最新信息...',
					delay: hasDeepThink ? 3000 : 800
				});
			}
			
			// 生成回答内容
			const answerParts = this._generateMockAnswer(userContent, aiOptions);
			answerParts.forEach((part, index) => {
				responseSteps.push({
					type: 'text',
					data: part,
					delay: (hasDeepThink ? 3500 : 1200) + (index * 200)
				});
			});
			
			// 添加结束标记
			responseSteps.push({
				type: 'tag',
				data: '[DONE]',
				delay: (hasDeepThink ? 3500 : 1200) + (answerParts.length * 200) + 500
			});
			
			// 按时序分发模拟消息
			responseSteps.forEach(({ type, data, delay }) => {
				setTimeout(() => {
					this._dispatchMockMessage(data, type);
				}, delay);
			});
			
		} catch (error) {
			this._log('error', 'Mock AI回答生成失败', error);
		}
	}
	
	/**
	 * 分发Mock消息
	 * 模拟WebSocket消息分发机制
	 * @private
	 * @param {string} data 消息数据
	 * @param {string} messageType 消息类型
	 */
	_dispatchMockMessage(data, messageType) {
		const mockMessage = {
			data: data,
			type: messageType,
			timeStamp: Date.now(),
			mockMode: true
		};
		
		// 分发消息到订阅者（复用现有的分发逻辑）
		this._dispatchMessage(mockMessage);
	}
	
	/**
	 * 启动心跳检测
	 * @private
	 */
	_startHeartbeat() {
		if (this.config.mockMode || !this.config.heartbeat.enabled || this.config.heartbeat.interval <= 0) {
			return;
		}
		
		this._stopHeartbeat();
		this._log('debug', '启动心跳检测', { interval: this.config.heartbeat.interval });
		
		this.heartbeatTimer = setInterval(() => {
			this._sendHeartbeat();
		}, this.config.heartbeat.interval);
	}
	
	/**
	 * 停止心跳检测
	 * @private
	 */
	_stopHeartbeat() {
		if (this.heartbeatTimer) {
			clearInterval(this.heartbeatTimer);
			this.heartbeatTimer = null;
		}
		
		if (this.heartbeatTimeoutTimer) {
			clearTimeout(this.heartbeatTimeoutTimer);
			this.heartbeatTimeoutTimer = null;
		}
	}
	
	/**
	 * 发送心跳包
	 * @private
	 */
	_sendHeartbeat() {
		if (!this.isConnected) {
			this._stopHeartbeat();
			return;
		}
		
		this.lastHeartbeatTime = Date.now();
		const heartbeatMessage = typeof this.config.heartbeat.message === 'string' 
			? this.config.heartbeat.message 
			: JSON.stringify({ ...this.config.heartbeat.message, timestamp: this.lastHeartbeatTime });
		
		this.socketTask.send({
			data: heartbeatMessage,
			success: () => {
				this.heartbeatStats.sent++;
				this._log('debug', '心跳包发送成功');
				
				this.heartbeatTimeoutTimer = setTimeout(() => {
					this.heartbeatLoseCount++;
					this.heartbeatStats.lost++;
					this._log('warn', '心跳响应超时');
					this._emit('heartbeatTimeout', {
						timeout: this.config.heartbeat.timeout,
						loseCount: this.heartbeatLoseCount,
						timestamp: Date.now()
					});
					
					if (this.heartbeatLoseCount >= this.config.heartbeat.loseLimit) {
						this._log('error', '心跳丢失次数超限，触发重连');
						this._handleReconnect();
					}
				}, this.config.heartbeat.timeout);
			},
			fail: (error) => {
				this._log('error', '心跳包发送失败', error);
				this._handleReconnect();
			}
		});
	}
	
	/**
	 * 判断是否为心跳响应
	 * @private
	 * @param {Object} res 消息对象
	 * @returns {boolean} 是否为心跳响应
	 */
	_isHeartbeatResponse(res) {
		try {
			if (typeof res.data === 'string') {
				if (res.data === 'pong' || res.data === 'ping') return true;
				
				const data = JSON.parse(res.data);
				return data && (data.type === 'pong' || data.type === 'ping');
			}
			return false;
		} catch {
			return false;
		}
	}
	
	/**
	 * 处理心跳响应
	 * @private
	 */
	_handleHeartbeatResponse() {
		if (this.heartbeatTimeoutTimer) {
			clearTimeout(this.heartbeatTimeoutTimer);
			this.heartbeatTimeoutTimer = null;
		}
		
		const responseTime = Date.now() - this.lastHeartbeatTime;
		this.heartbeatLoseCount = 0;
		this.heartbeatStats.received++;
		
		// 计算平均响应时间
		const { received, avgResponseTime } = this.heartbeatStats;
		this.heartbeatStats.avgResponseTime = ((avgResponseTime * (received - 1)) + responseTime) / received;
		
		this._log('debug', '收到心跳响应', { responseTime: responseTime + 'ms' });
	}
	
	/**
	 * 处理重连逻辑
	 * @private
	 */
	_handleReconnect() {
		if (this.reconnectLock || !this.config.reconnect.enabled) {
			return;
		}
		
		if (this.currentReconnectAttempts >= this.config.reconnect.maxAttempts) {
			this._log('warn', '重连次数已达上限，停止重连');
			this._emit('reconnectFailed', {
				attempts: this.currentReconnectAttempts,
				maxAttempts: this.config.reconnect.maxAttempts,
				reason: '达到最大重连次数'
			});
			return;
		}
		
		this.reconnectLock = true;
		this.currentReconnectAttempts++;
		this._setState('reconnecting');
		
		let delay = this.config.reconnect.baseDelay;
		if (this.config.reconnect.useExponentialBackoff) {
			delay = Math.min(
				this.config.reconnect.baseDelay * Math.pow(2, this.currentReconnectAttempts - 1),
				this.config.reconnect.maxDelay
			);
		}
		
		this._log('info', `准备第${this.currentReconnectAttempts}次重连`, { delay });
		this._emit('reconnecting', { attempts: this.currentReconnectAttempts, delay });
		
		this.reconnectTimer = setTimeout(async () => {
			this.reconnectLock = false;
			
			try {
				await this.connect();
				this.stats.reconnections++;
				this._log('info', '重连成功');
				this._emit('reconnected', { attempts: this.currentReconnectAttempts });
			} catch (error) {
				this._log('error', '重连失败', error);
				if (this.currentReconnectAttempts < this.config.reconnect.maxAttempts) {
					this._handleReconnect();
				}
			}
		}, delay);
	}
	
	/**
	 * 停止重连
	 * @private
	 */
	_stopReconnect() {
		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer);
			this.reconnectTimer = null;
		}
	}
	
	/**
	 * 停止批量发送
	 * @private
	 */
	_stopBatchSend() {
		if (this.batchSendTimer) {
			clearTimeout(this.batchSendTimer);
			this.batchSendTimer = null;
		}
	}
	
	/**
	 * 处理AI消息
	 * @private
	 * @param {Object} messageObj 消息对象
	 * @param {Object} rawMessage 原始消息
	 */
	_handleAIMessage(messageObj, rawMessage) {
		// AI对话特殊处理逻辑
		if (this.deepThinkMode && rawMessage.data === '[TEXT]') {
			this.deepThinkMode = false;
			const thinkTime = Date.now() - this.deepThinkStartTime;
			this._log('info', '深度思考模式结束', { duration: thinkTime });
		}
	}
	
	/**
	 * 压缩消息
	 * @private
	 * @param {string} message 原始消息
	 * @returns {string} 压缩后的消息
	 */
	_compressMessage(message) {
		try {
			// 简单压缩实现
			const compressed = message.replace(/(.)\1{2,}/g, (match, char) => {
				return `${char}[${match.length}]`;
			});
			
			if (compressed.length < message.length) {
				return JSON.stringify({
					type: 'compressed',
					data: compressed,
					originalLength: message.length
				});
			}
		} catch (error) {
			this._log('warn', '消息压缩失败', error);
		}
		
		return message;
	}
	
	/**
	 * 生成模拟回答内容（Mock模式专用）
	 * @private
	 * @param {string} message 用户消息
	 * @param {Object} options 发送选项
	 * @returns {Array} 回答内容数组
	 */
	_generateMockAnswer(message, options) {
		const parts = [];
		
		if (options.deepThink) {
			parts.push('经过深度思考，我认为');
		}
		
		if (options.webSearch) {
			parts.push('根据最新的网络信息，');
		}
		
		// 根据消息内容生成不同的回答
		if (message.includes('图表') || message.includes('数据')) {
			parts.push('我为您生成了相关的数据图表');
		} else if (message.includes('方案') || message.includes('计划')) {
			parts.push('我为您制定了详细的执行方案');
		} else if (message.includes('分析') || message.includes('评估')) {
			parts.push('以下是我的专业分析结果');
		} else {
			parts.push('根据您的问题，我的回答是');
		}
		
		parts.push('：这是一个很好的问题。');
		parts.push('基于我的理解，我建议您可以从以下几个方面考虑：');
		parts.push('\n\n1. 首先需要明确目标和需求');
		parts.push('\n2. 然后制定具体的实施步骤');  
		parts.push('\n3. 最后要建立效果评估机制');
		parts.push('\n\n希望这个回答对您有所帮助！');
		
		return parts;
	}
	
	/**
	 * 队列消息
	 * @private
	 * @param {string} message 消息内容
	 * @param {Object} options 发送选项
	 * @returns {Promise<string>} 队列结果
	 */
	_queueMessage(message, options) {
		return new Promise((resolve, reject) => {
			const queueItem = { 
				data: message, 
				resolve, 
				reject, 
				options,
				timestamp: Date.now()
			};
			
			if (options.priority) {
				this.priorityQueue.unshift(queueItem);
			} else {
				this.messageQueue.push(queueItem);
			}
			
			// 检查队列长度限制
			const totalQueueSize = this.messageQueue.length + this.priorityQueue.length;
			if (totalQueueSize > this.config.queue.maxSize) {
				const removed = this.messageQueue.shift() || this.priorityQueue.pop();
				if (removed) {
					removed.reject(new Error('消息队列已满，消息被丢弃'));
				}
			}
			
			this._log('debug', 'WebSocket未连接，消息已加入队列', { 
				queueSize: totalQueueSize,
				priority: options.priority 
			});
		});
	}
	
	/**
	 * 处理消息用于发送
	 * @private
	 * @param {string} message 原始消息
	 * @param {Object} options 发送选项
	 * @returns {Promise<string>} 处理后的消息
	 */
	async _processMessageForSending(message, options) {
		// 压缩处理
		if (options.compress !== false && this.config.compression.enabled) {
			if (message.length >= this.config.compression.threshold) {
				const compressed = this._compressMessage(message);
				if (compressed.length < message.length * 0.8) {
					this.compressionStats.messagesCompressed++;
					this.compressionStats.totalOriginalSize += message.length;
					this.compressionStats.totalCompressedSize += compressed.length;
					this.compressionStats.compressionRatio = 
						this.compressionStats.totalCompressedSize / this.compressionStats.totalOriginalSize;
					return compressed;
				}
			}
		}
		
		return message;
	}
	
	/**
	 * 刷新消息队列
	 * @private
	 */
	_flushMessageQueue() {
		if (!this.config.queue.enabled || this.queueProcessing) {
			return;
		}
		
		const totalQueue = [...this.priorityQueue, ...this.messageQueue];
		if (totalQueue.length === 0) return;
		
		this._log('info', `开始发送消息队列中的${totalQueue.length}条消息`);
		this.queueProcessing = true;
		this.messageQueue = [];
		this.priorityQueue = [];
		
		// 异步发送队列消息
		Promise.allSettled(totalQueue.map(async (item, index) => {
			try {
				if (index > 0) await this._delay(100);
				
				if (!this.isConnected) {
					throw new Error('连接已断开，无法发送队列消息');
				}
				
				const result = await this._executeSend(item.data, item.options, `queue_${index}`);
				item.resolve(result);
			} catch (error) {
				item.reject(error);
			}
		})).finally(() => {
			this.queueProcessing = false;
		});
	}
}

export default WebSocketManager;